//
//  WhyViewController.m
//  天气预报
//
//  Created by Maggie on 14-8-27.
//  Copyright (c) 2014年 fmning. All rights reserved.
//



#import "WhyViewController.h"
#define kWeatherForBeijinAPI @"http://www.weather.com.cn/data/sk/101010100.html"

#define kLocationAPI @"http://maps.googleapis.com/maps/api/geocode/json?address=suzhou&sensor=true"

@interface WhyViewController ()
- (IBAction)sendSynchronousRequest:(id)sender;

- (IBAction)getWeather:(id)sender;
- (IBAction)sendAsynchronousRequestUseBlock:(id)sender;
@property (weak, nonatomic) IBOutlet UILabel *infoLable;

@end

@implementation WhyViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 发送同步请求
- (IBAction)sendSynchronousRequest:(id)sender {
    self.infoLable.text = @"北京天气如何?";
    
    NSURL *url = [NSURL URLWithString:kWeatherForBeijinAPI];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
    [request setURL:url];
    [request setHTTPMethod:@"GET"];

    
    //发送同步请求，data就是返回的数据
    NSError *error = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
    
    if (data == nil) {
        NSLog(@"fail!");
        return;
    }
    
    //解析JSON
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"%@",dic);
    
    NSDictionary *weatherDic = [dic objectForKey:@"weatherinfo"];
    self.infoLable.text = [NSString stringWithFormat:@"%@,%@摄氏度,%@ %@",
                           [weatherDic objectForKey:@"city"],
                           [weatherDic objectForKey:@"temp"],
                           [weatherDic objectForKey:@"WD"],
                           [weatherDic objectForKey:@"WS"]];
    
}


#pragma mark - iOS5.0 SDK NSURLConnection类新增的sendAsynchronousRequest:queue:completionHandler:方法 ，使用block快捷方便发送异步请求

- (IBAction)sendAsynchronousRequestUseBlock:(id)sender {
    self.infoLable.text = @"北京天气如何?";
    
    NSURL *url = [NSURL URLWithString:kWeatherForBeijinAPI];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
    
//    创建线程队列，将异步请求线程添加到队列中
//    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    
    //发送异步请求，请求接收执行block函数
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError != nil) {
            NSLog(@"请求失败，%@",connectionError.localizedDescription);
        }
        else{
            //解析JSON
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSLog(@"%@",dic);
            
            NSDictionary *weatherDic = [dic objectForKey:@"weatherinfo"];
            self.infoLable.text = [NSString stringWithFormat:@"%@,%@摄氏度,%@ %@",
                                   [weatherDic objectForKey:@"city"],
                                   [weatherDic objectForKey:@"temp"],
                                   [weatherDic objectForKey:@"WD"],
                                   [weatherDic objectForKey:@"WS"]];
        }
    }];
}
#pragma mark - 发送异步请求，使用委托
- (IBAction)getWeather:(id)sender {
    self.infoLable.text = @"北京天气如何?";
    
    //显示网络请求指示符
    if (![UIApplication sharedApplication].isNetworkActivityIndicatorVisible) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    }
    
    NSURL *url = [NSURL URLWithString:kWeatherForBeijinAPI];
    //根据NSURL创建请求(此处为可扩展请求)
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    //发送异步请求建立连接，同时设置委托对象
    [NSURLConnection connectionWithRequest:request delegate:self];
}

#pragma mark - 请求成功，接收返回数据
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"didReceiveData");
    //获取json字符串
//    NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//    NSLog(@"%@",json);
    
    //解析JSON
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//    NSLog(@"%@",dic);
    
    NSDictionary *weatherDic = [dic objectForKey:@"weatherinfo"];
    self.infoLable.text = [NSString stringWithFormat:@"%@,%@摄氏度,%@ %@",
                           [weatherDic objectForKey:@"city"],
                           [weatherDic objectForKey:@"temp"],
                           [weatherDic objectForKey:@"WD"],
                           [weatherDic objectForKey:@"WS"]];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

#pragma mark - 数据请求失败
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"无法获取数据，请检查网络" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [connection cancel];
}

@end







